#!/usr/bin/env python
import os
import sys
import random
from datetime import datetime, timedelta
from django.utils import timezone

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IPaddress.settings')
import django
django.setup()

from index.models import Data_date, Access_ip
from django.db import transaction

def generate_test_data():
    """生成2025年9月10日到21日的测试数据"""
    start_date = datetime(2025, 9, 10).date()
    end_date = datetime(2025, 9, 21).date()
    
    # 测试IP地址池
    test_ips = [
        '192.168.1.10', '192.168.1.11', '192.168.1.12', '192.168.1.13',
        '192.168.1.20', '192.168.1.21', '192.168.1.22', '192.168.1.23',
        '10.0.0.15', '10.0.0.16', '10.0.0.17', '10.0.0.18',
        '172.16.0.25', '172.16.0.26', '172.16.0.27', '172.16.0.28',
        '8.8.8.8', '1.1.1.1', '9.9.9.9', '208.67.222.222'
    ]
    
    current_date = start_date
    
    while current_date <= end_date:
        print(f"正在处理日期: {current_date}")
        
        # 创建日期记录
        data_date, created = Data_date.objects.get_or_create(
            date=current_date,
            defaults={'date': current_date}
        )
        
        if created:
            print(f"  ✓ 创建新日期记录: {current_date}")
        else:
            print(f"  - 使用现有日期记录: {current_date}")
        
        # 为这一天生成访问记录
        # 每天的访问量：50-200次
        daily_visits = random.randint(50, 200)
        print(f"  生成 {daily_visits} 条访问记录...")
        
        # 使用事务批量创建访问记录
        with transaction.atomic():
            access_records = []
            
            for i in range(daily_visits):
                # 随机选择一个IP
                ip_address = random.choice(test_ips)
                
                # 随机生成一天内的时间
                hour = random.randint(0, 23)
                minute = random.randint(0, 59)
                second = random.randint(0, 59)
                
                # 创建访问时间
                access_time = timezone.make_aware(
                    datetime.combine(current_date, datetime.min.time().replace(
                        hour=hour, minute=minute, second=second
                    ))
                )
                
                # 创建访问记录对象
                access_record = Access_ip(
                    ip_address=ip_address,
                    date=data_date,
                    exact_time=access_time
                )
                access_records.append(access_record)
            
            # 批量创建访问记录
            Access_ip.objects.bulk_create(access_records)
        
        print(f"  ✓ 完成 {daily_visits} 条访问记录的创建")
        
        # 移动到下一天
        current_date += timedelta(days=1)
    
    print("\n" + "="*50)
    print("测试数据生成完成！")
    print("="*50)
    
    # 显示统计信息
    total_dates = Data_date.objects.count()
    total_accesses = Access_ip.objects.count()
    print(f"总日期记录数: {total_dates}")
    print(f"总访问记录数: {total_accesses}")
    
    # 显示每天的统计
    print("\n每日访问统计:")
    for data_date in Data_date.objects.order_by('date'):
        access_count = data_date.access_ip_set.count()
        print(f"  {data_date.date}: {access_count} 次访问")

if __name__ == "__main__":
    print("开始生成2025年9月10日到21日的测试数据...")
    print("="*50)
    
    try:
        generate_test_data()
        print("\n✓ 测试数据生成成功！")
    except Exception as e:
        print(f"\n✗ 生成测试数据时出错: {e}")
        import traceback
        traceback.print_exc()